//TerminalConnector.js
export class TerminalConnector {
  private ws: any;
  public handleOpen: any;
  public handleMessage: any;
  public handleClose: any;
  public handleError: any;
  constructor({// @ts-ignore
    handleOpen, // @ts-ignore
    handleMessage, // @ts-ignore
    handleClose, // @ts-ignore
    handleError,
  }) {
    this.handleOpen = handleOpen;
    this.handleMessage = handleMessage;
    this.handleClose = handleClose;
    this.handleError = handleError;
    this.ws = new WebSocket("ws://139.198.154.153:8090/ws/shell");
    this.ws.onopen = this.onConnOpen;
    this.ws.onmessage = this.onMessage;
    this.ws.onclose = this.onConnClose;
    this.ws.onerror = this.onConnError;
  }
  handleSend(data: any) {
    this.ws.send(data);
  }
  detachTerminal() {
    try {
      this.ws.close();
      this.ws = null;
    } catch (e) {
      console.warn(e);
    }
  }
  private onConnOpen = () => {
    const msg = { operation: "stdin", data: "export TERM=xterm && clear \r" }
    this.ws.send(JSON.stringify(msg))
  }
  private onMessage = (event: any) => {
    const msg = JSON.parse(event.data)
    if (msg.operation === "stdout") {
      this.handleMessage(msg.data)
    } else {
      console.log("invalid msg operation: " + msg)
    }
  }
  private onConnClose = (e: any) => {
    console.log("conn close", e);
    this.handleClose();
  }
  private onConnError = (e: any) => {
    console.error("conn error", e);
    this.handleError(e);
  }

}